package com.zmn.oms.dubbo.impl.zmn.shop.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.price.common.dto.ProductPriceDRO;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.common.constant.FicoConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.CancelOrderDIO;
import com.zmn.oms.dubbo.dto.zmn.order.NewOrderDRO;
import com.zmn.oms.dubbo.dto.zmn.order.OrderDiscountDIO;
import com.zmn.oms.dubbo.dto.zmn.order.shop.NewShopOrderDIO;
import com.zmn.oms.dubbo.dto.zmn.order.shop.OrderAmountByCalcDIO;
import com.zmn.oms.dubbo.dto.zmn.order.shop.OrderAmountByCalcDRO;
import com.zmn.oms.dubbo.dto.zmn.order.shop.UpdateQuotationOrderProductDIO;
import com.zmn.oms.dubbo.dto.zmn.serviceitem.OrderServiceItemDIO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.shop.order.ShopOrderRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.orderamount.DiscountCalculateResultDTO;
import com.zmn.oms.model.dto.orderamount.DiscountDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyQuotationDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：店铺工单
 * @author heciqi
 * @date 2019/08/21 18:25
 */
@Deprecated
@Service(loadbalance = "roundrobin", timeout = 20000, retries = 2, version = DubboConsts.INTERFACE_VERSION)
public class ShopOrderRemoteServiceImpl extends OrderBaseRemoteService implements ShopOrderRemoteService {

	static final String TAG = "SAAS-店铺单";

	@Autowired
	private OrderAmountBService orderAmountBService;

	/**
	 * 获取订单金额
	 *
	 * @param orderAmountByCalcDIO
	 * @return
	 */
	@Override
	public com.zmn.common.dto2.ResponseDTO<OrderAmountByCalcDRO> getOrderAmountByCalc(OrderAmountByCalcDIO orderAmountByCalcDIO) {
		logger.info("[{}] 获取订单价格-请求：getOrderAmountByCalc={}", TAG, JSON.toJSONString(orderAmountByCalcDIO));
		ValidateResult validateResult = ValidatorUtil.validator(orderAmountByCalcDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return com.zmn.common.dto2.ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}

		com.zmn.common.dto2.ResponseDTO<ProductPriceDRO> ResponseProductPriceDRO = orderAmountBService.getProductPriceDRO(orderAmountByCalcDIO.getCityId(), orderAmountByCalcDIO.getChannelId(), orderAmountByCalcDIO.getShowProductId());
		if (!ResponseProductPriceDRO.isSuccess()) {
			return com.zmn.common.dto2.ResponseDTO.fail(ResponseProductPriceDRO.getMessage());
		}

		// 无产品价格
		ProductPriceDRO productPriceDRO = ResponseProductPriceDRO.getData();
		if (productPriceDRO == null) {
			return com.zmn.common.dto2.ResponseDTO.success(
					OrderAmountByCalcDRO.builder()
							.haveAmount(GlobalConsts.NO).build()
			);
		}

		// 获取支付金额
		Integer payAmount = orderAmountBService.getPayAmount(productPriceDRO, 1);
		Integer discountAmount = null;
		List<DiscountDTO> list = Lists.newArrayList();
		// 优惠处理
		if (NumberUtil.isNotNullOrZero(payAmount)) {
			try {
				// 优惠券优惠
				DiscountDTO couponDiscount = orderAmountBService.getCouponDiscount(orderAmountByCalcDIO.getCityId(), orderAmountByCalcDIO.getChannelId(),
						orderAmountByCalcDIO.getShowProductId(), orderAmountByCalcDIO.getUserId(), orderAmountByCalcDIO.getItemCode(), payAmount);
				if (couponDiscount != null) {
					list.add(couponDiscount);
				}
				// 一口价优惠
				if (Objects.equals(orderAmountByCalcDIO.getUsePayDiscount(), GlobalConsts.YES)) {
					DiscountDTO finalPriceDiscount = orderAmountBService.getFinalPriceDiscount(productPriceDRO);
					if (finalPriceDiscount != null) {
						list.add(finalPriceDiscount);
					}
				}
			} catch (OmsBaseException e) {
				return com.zmn.common.dto2.ResponseDTO.fail(e.getMessage());
			}
			// 计算优惠
			DiscountCalculateResultDTO discountCalculateResultDTO = orderAmountBService.calculateDiscount(list, payAmount);
			if (discountCalculateResultDTO != null) {
				payAmount = discountCalculateResultDTO.getAfterDiscountAmount();
				discountAmount = discountCalculateResultDTO.getDiscountAmount();
			}
		}

		OrderAmountByCalcDRO orderAmountByCalcDRO = new OrderAmountByCalcDRO();
		orderAmountByCalcDRO.setHaveAmount(GlobalConsts.YES);
		orderAmountByCalcDRO.setOriginalAmount(productPriceDRO.getPrice());
		orderAmountByCalcDRO.setPayAmount(payAmount);
		orderAmountByCalcDRO.setDiscountAmount(discountAmount);
		orderAmountByCalcDRO.setPrepayType(Optional.ofNullable(productPriceDRO.getPayType()).orElse(2));// 默认下单后支付
		orderAmountByCalcDRO.setFinalPrice(Objects.equals(productPriceDRO.getItemStandard(), GlobalConsts.YES) ? GlobalConsts.YES : GlobalConsts.NO);
		orderAmountByCalcDRO.setOrderServiceItemList(Lists.newArrayList(this.convertToDiscountDIO(productPriceDRO.getItemDRO())));
		orderAmountByCalcDRO.setOrderDiscountList(this.convertToDiscountDIO(list));
		logger.info("[{}] 获取订单价格-返回：getOrderAmountByCalc={}", TAG, orderAmountByCalcDRO);
		return com.zmn.common.dto2.ResponseDTO.success(orderAmountByCalcDRO);
	}

	private List<OrderDiscountDIO> convertToDiscountDIO(List<DiscountDTO> discountDTOS) {
		List<OrderDiscountDIO> list = Lists.newArrayList();
		if (CollectionUtil.isNullOrEmpty(discountDTOS)) {
			return list;
		}
		for (DiscountDTO discountDTO : discountDTOS) {
			OrderDiscountDIO orderDiscountDIO = new OrderDiscountDIO();
			orderDiscountDIO.setCateg(discountDTO.getDiscountCateg());
			orderDiscountDIO.setCategName(FicoConsts.getDiscountCategName(discountDTO.getDiscountCateg()));
			if (Objects.equals(discountDTO.getBatchId(), 10002)) {
				orderDiscountDIO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
			} else {
				orderDiscountDIO.setType(discountDTO.getPreferentialType());
			}
			orderDiscountDIO.setAmount(discountDTO.getDiscountAmount());
			orderDiscountDIO.setTypeDesc("");
			orderDiscountDIO.setSourceId(discountDTO.getBatchId());
			orderDiscountDIO.setSourceData(discountDTO.getDiscountSourceData());
			orderDiscountDIO.setRemark(discountDTO.getItemCode());
			list.add(orderDiscountDIO);
		}
		return list;
	}

	private OrderServiceItemDIO convertToDiscountDIO(ItemDRO itemDRO) {
		if (itemDRO==null) {
			return null;
		}
		OrderServiceItemDIO orderServiceItemDIO = new OrderServiceItemDIO();
		orderServiceItemDIO.setServItemId(itemDRO.getItemId());
		orderServiceItemDIO.setServItemName(itemDRO.getItemName());
		orderServiceItemDIO.setInternalSettlementPrice(itemDRO.getPriceInternalSettlement());
		orderServiceItemDIO.setExternalSettlementPrice(itemDRO.getPriceExternalSettlement());
		orderServiceItemDIO.setNumber(1);
		orderServiceItemDIO.setItemPrice(itemDRO.getPrice());
		return orderServiceItemDIO;
	}


	/**
	 * 新单
	 * @param newOrderDIO
	 * @return
	 */
	@Override
	public ResponseDTO<NewOrderDRO> addOrder(NewShopOrderDIO newOrderDIO) {

		logger.info("[{}] 添加店铺订单：NewShopOrderDIO={}", TAG, JSON.toJSONString(newOrderDIO));

		ValidateResult validateResult = ValidatorUtil.validator(newOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
		}
		if (StringUtils.isBlank(newOrderDIO.getOperator())) {
			newOrderDIO.setOperator("系统");
		}

		// DIO转换
		ZsNormalNewOrderDTO normalNewOrderDTO = BeanMapper.map(newOrderDIO, ZsNormalNewOrderDTO.class);
		normalNewOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
		logger.info("未替换下单接口：[com.zmn.oms.dubbo.impl.zmn.shop.order.ShopOrderRemoteServiceImpl.addOrder]，下单渠道：[{}]，下单方式：[{}]", normalNewOrderDTO.getChannelId(), normalNewOrderDTO.getReceiveEntranceId());
		return super.addOrder(normalNewOrderDTO);
	}

	/**
	 * 新增计价器订单
	 * @param newOrderDIO
	 * @return
	 */
	@Override
	public com.zmn.common.dto2.ResponseDTO<NewOrderDRO> addQuotationOrder(NewShopOrderDIO newOrderDIO) {

		logger.info("[{}] 添加计价器订单：NewShopOrderDIO={}", TAG, JSON.toJSONString(newOrderDIO));

		ValidateResult validateResult = ValidatorUtil.validator(newOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return com.zmn.common.dto2.ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}
		if (StringUtils.isBlank(newOrderDIO.getOperator())) {
			newOrderDIO.setOperator("系统");
		}

        // DIO转换
        ZsNormalNewOrderDTO normalNewOrderDTO = BeanMapper.map(newOrderDIO, ZsNormalNewOrderDTO.class);
        normalNewOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
        normalNewOrderDTO.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_FAULT);
        normalNewOrderDTO.setQuotationType(GlobalConsts.OPERATE_USER_TYPE_USER);

		logger.info("未替换下单接口：[com.zmn.oms.dubbo.impl.zmn.shop.order.ShopOrderRemoteServiceImpl.addQuotationOrder]，下单渠道：[{}]，下单方式：[{}]", normalNewOrderDTO.getChannelId(), normalNewOrderDTO.getReceiveEntranceId());
        ResponseDTO<NewOrderDRO> oldResponse = super.addOrder(normalNewOrderDTO);

		if (oldResponse.getStatusBool() && oldResponse.getData() != null) {
			return com.zmn.common.dto2.ResponseDTO.success(oldResponse.getData(), oldResponse.getMessage());
		}
		else {
			return com.zmn.common.dto2.ResponseDTO.fail(oldResponse.getMessage());
		}
	}

	/**
	 * 修改计价器订单产品及服务项（仅用于修改【计价器类型】的订单产品）
	 * @param updateQuotationOrderProductDIO
	 * @return
	 */
	@Override
	public com.zmn.common.dto2.ResponseDTO<Boolean> updateQuotationOrderProduct(UpdateQuotationOrderProductDIO updateQuotationOrderProductDIO) {
		logger.info("[{}] 修改计价器订单产品：UpdateQuotationOrderProductDIO={}", TAG,
                JSON.toJSONString(updateQuotationOrderProductDIO));

		ValidateResult validateResult = ValidatorUtil.validator(updateQuotationOrderProductDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return com.zmn.common.dto2.ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}
		if (StringUtils.isBlank(updateQuotationOrderProductDIO.getOperator())) {
			updateQuotationOrderProductDIO.setOperator("系统");
		}

		ModifyQuotationDTO modifyQuotationDTO = BeanMapper.map(updateQuotationOrderProductDIO, ModifyQuotationDTO.class);
		modifyQuotationDTO.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_FAULT);
		modifyQuotationDTO.setQuotationType(updateQuotationOrderProductDIO.getOperatorType());
		modifyQuotationDTO.setOperator(updateQuotationOrderProductDIO.getOperator());
		ResponseDTO<Boolean> oldResponse = super.updateOrderProduct(modifyQuotationDTO);

		if (oldResponse.getStatusBool() && oldResponse.getData() != null) {
			return com.zmn.common.dto2.ResponseDTO.success(oldResponse.getData(), oldResponse.getMessage());
		}
		else {
			return com.zmn.common.dto2.ResponseDTO.fail(oldResponse.getMessage());
		}
	}

	/**
	 * 取消订单
	 *
	 * @param cancelOrderDIO
	 * @return
	 */
	@Override
	public ResponseDTO cancelOrder(CancelOrderDIO cancelOrderDIO) {
		logger.info("[{}] 取消店铺订单：CancelOrderDIO={}", TAG, JSON.toJSONString(cancelOrderDIO));

		ValidateResult validateResult = ValidatorUtil.validator(cancelOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误");
		}

		cancelOrderDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_USER);
		return super.cancelOrder(cancelOrderDIO);
	}
}
